package com.example.mycityapp;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.mycityapp.BrowsePictureActivity.BrowsePictureForWhat;
import com.example.mycityapp.util.ImageDownloader;
import com.example.mycityapp.util.StringReplacer;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentSender;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.IntentSender.SendIntentException;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.Resources.Theme;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.UserHandle;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class ProfilePage extends Activity {
	public static ProfilePage instance;
	public static String postViewPostId;
	public static String imgurIdForChangedProfilePic;
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.profilepage);
		instance = ProfilePage.this;
		TextView userNameTextView = (TextView) findViewById(R.id.userNameSurname);
		LinearLayout layout = (LinearLayout) findViewById(R.id.profilePageRealLinearLayout); 
		userNameTextView.setText(MainActivity.firstName + " " + MainActivity.lastName);
		EditText userBioEditText = (EditText) findViewById(R.id.editTextBio);
		ImageView userProfilePic = (ImageView) findViewById(R.id.profilepicReal);
		RelativeLayout.LayoutParams layoutParamsReal = new RelativeLayout.LayoutParams(160, 160);
		userProfilePic.setLayoutParams(layoutParamsReal);
		String urlGetUser = "http://titan.cmpe.boun.edu.tr:8087/MyCity/services/user/getUserById?userId=" + MainActivity.userId;
		JSONParser jParser = new JSONParser();
		String jsonUser = jParser.doInBackground(urlGetUser);
		try {
			JSONObject objectUser = new JSONObject(jsonUser);
			userBioEditText.setText(objectUser.getString("bio"));
			String imgurId = objectUser.getString("profilePic");
			if(!imgurId.contains("null")){
				ImageDownloader.download("http://i.imgur.com/"+ imgurId +".jpg", userProfilePic, false);
			}
			
			
			
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		
		String url = "http://titan.cmpe.boun.edu.tr:8087/MyCity/services/user/showAllPosts?userId=" + MainActivity.userId;
		JSONArray posts = null;

		String json = jParser.doInBackground(url);
		try {
			int numberOfPostsToView = 4;
			posts = new JSONArray(json);
			for(int i = posts.length() - 1; i >= 0 && numberOfPostsToView > 0; i--){
				numberOfPostsToView --;
				JSONObject object = posts.getJSONObject(i);
				String postContent = object.getString("postContent"); 
				String postDate = object.getString("postDate"); 
				String postType = object.getString("postType"); 
				String locationName = object.getString("locationName"); 
				String tags = object.getString("tags");
				String userId = object.getString("userId");
				final String postId = object.getString("postId");
				
				url = "http://titan.cmpe.boun.edu.tr:8087/MyCity/services/user/getUserById?userId=" + userId;
				json = jParser.doInBackground(url);
				JSONObject userObject = new JSONObject(json);
				String postUserFirstName = userObject.getString("firstName");
				String postUserLastName = userObject.getString("lastName");
				
				TextView postContentTextView = new TextView(this);
				postContentTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
				postContentTextView.setGravity(Gravity.CENTER);
				postContentTextView.setId(i);
				postContentTextView.setTextColor(Color.WHITE);
				postContentTextView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

				LinearLayout layoutSeeFullPostButton = new LinearLayout(this);
				layout.addView(layoutSeeFullPostButton);
				layoutSeeFullPostButton.setOrientation(LinearLayout.HORIZONTAL);
				layoutSeeFullPostButton.setGravity(Gravity.CENTER);
				layoutSeeFullPostButton.setId(i);

				layout.addView(postContentTextView);
				
				if (postType.contains("2"))
				{
					ImageView postImageView = new ImageView(getBaseContext());
					int specialCharIndex = postContent.indexOf("|");
					
					String imgurId = postContent.substring(specialCharIndex + 1);
					postContent = postContent.substring(0, specialCharIndex);
					postImageView.setImageResource(R.drawable.ic_launcher);
					//ImageDownloader.download("http://i.imgur.com/"+imgurId+".jpg", postImageView, false);
					LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(160, 120);
					layoutParams.gravity = Gravity.CENTER;
					postImageView.setLayoutParams(layoutParams);
					layoutSeeFullPostButton.addView(postImageView);
				}
				postContentTextView.setText(postUserFirstName + " " + postUserLastName + ":\n " + postContent);
				
				Button seeFullPostButton = new Button(this);
				seeFullPostButton.setText("See Full Post");
				seeFullPostButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
				seeFullPostButton.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
				seeFullPostButton.setId(i);
				seeFullPostButton.setTextColor(Color.WHITE);
				seeFullPostButton.setBackgroundColor(Color.DKGRAY);
				seeFullPostButton.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						postViewPostId = postId;
						startActivity(new Intent(ProfilePage.this, PostViewPage.class));
						
					}
				});
				layoutSeeFullPostButton.addView(seeFullPostButton);
				
				TextView postContentTextView2 = new TextView(this);
				postContentTextView2.setText("(" + postDate + ")\n" + tags + "\nLocation: " + locationName + "\n");
				postContentTextView2.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
				postContentTextView2.setGravity(Gravity.CENTER);
				postContentTextView2.setId(i);
				postContentTextView2.setTextColor(Color.WHITE);
				postContentTextView2.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
				layout.addView(postContentTextView2);
				
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Button updateBioButton = (Button) findViewById(R.id.updateBioButton);
		updateBioButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				EditText userBioEditText = (EditText) findViewById(R.id.editTextBio);
				String newUserBio = userBioEditText.getText().toString();
				newUserBio = StringReplacer.Encode(newUserBio);
				String urlUpdateBio = "http://titan.cmpe.boun.edu.tr:8087/MyCity/services/user/updateBio?userId=" + MainActivity.userId + "&bio=" + newUserBio;
				JSONParser jParser = new JSONParser();
				String jsonUpdateBio = jParser.doInBackground(urlUpdateBio);
				if (jsonUpdateBio.contains("1"))
				{
					AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(ProfilePage.this);

                    dlgAlert.setMessage("User bio updated.");
                    dlgAlert.setTitle("Success");
                    dlgAlert.setPositiveButton("OK", null);
                    dlgAlert.setCancelable(true);
                    dlgAlert.create().show();

                    dlgAlert.setPositiveButton("Ok",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {

                        }
                    });
				}
				else
				{
					AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(ProfilePage.this);

                    dlgAlert.setMessage("Request failed. Sorry :(");
                    dlgAlert.setTitle("Error");
                    dlgAlert.setPositiveButton("OK", null);
                    dlgAlert.setCancelable(true);
                    dlgAlert.create().show();

                    dlgAlert.setPositiveButton("Ok",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {

                        }
                    });
				}
			}
		});
		

		Button changeProfilePicButton = (Button) findViewById(R.id.changeProfilePicButton);
		changeProfilePicButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				BrowsePictureActivity.browseType = BrowsePictureForWhat.ProfilePage;
				startActivity(new Intent(ProfilePage.this, BrowsePictureActivity.class));
			}
		});
	}
}
